<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2021/01/16
 * Time: 20:34
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\wms;

use app\admin\controller\BaseController;
use app\common\library\Tools;
use app\common\model\Account;
use app\common\model\ProductPlatformBarcode;
use app\common\model\ProductStore;
use app\common\service\product\PlatformService;
use think\facade\Validate;

/**
 * 平台二维码管理
 * Class BarcodeController
 * @package app\admin\controller\wms
 */
class PmbarcodeController extends BaseController
{
    /**
     * 平台条码首页
     * @return string
     * @date 2021/01/16
     * @author longli
     */
    public function index()
    {
        if($this->request->isAjax())
        {
            $barcode = ProductPlatformBarcode::with(['account'])->order("sort desc, barcode_id desc");
            $this->searchModel($barcode, [
                'eq' => ['account_id', 'is_merge', 'status'],
            ]);
            if($sku = $this->request->post('sku', '', 'trim'))
            {
                $skus = \app\common\model\Product::getSkusBySpu($sku);
                $barcode->whereIn('sku', !empty($skus) ? $skus : $sku);
            }
            $limit = $this->getPageSize();
            $barcode = $barcode->paginate($limit);
            $this->assign("list", $barcode->getCollection());
            $this->assign("page", $barcode->render());
            return $this->fetch("lists");
        }
        $this->assign("accounts", Account::getAll());
        $this->assign("is_merge", ["否", "是"]);
        $this->assign("status", ["否", "是"]);
        return $this->fetch("index");
    }

    /**
     * 添加平台条码
     * @date 2021/01/16
     * @author longli
     */
    public function add()
    {
        $barcodeId = $this->request->request("barcode_id");
        if(!empty($barcodeId)) $this->assign("barcode", ProductPlatformBarcode::get($barcodeId));
        $this->assign("accounts", Account::getAll());
        $this->assign("skus", ProductStore::field(["sku"])->order("sku")->select());
        return $this->fetch("add");
    }

    /**
     * 更新平台条码信息
     * @date 2021/01/16
     * @author longli
     */
    public function save()
    {
        if($this->request->isPost())
        {
            $validate = Validate::make([
                'account_id'  => 'require',
                'sku'  => 'require',
            ],[
                'account_id.require' => '账号必选',
                'sku.require' => 'SKU 必选',
            ]);
            $data = $this->request->post();
            if(!$validate->batch()->check($data)) $this->error(join(', ', $validate->getError()));
            if(!isset($data['status'])) $data['status'] = ProductPlatformBarcode::IS_YES;
            // 自动合成
            if(!empty($data['path_pdf']) && empty($data['merge_path_pdf']))
            {
                $rootPath = PlatformService::getRootPath($data['path_pdf']);
                $text = !empty($data['merge_text']) ? $data['merge_text'] : '';
                if(($toPath = $this->mergeBarcode($rootPath, $text)) !== false)
                {
                    $data['merge_path_pdf'] = $toPath;
                    $data['is_merge'] = ProductPlatformBarcode::IS_YES;
                }
            }
        }
        else
        {
            $validate = Validate::make([
                'barcode_id'  => 'require',
            ],[
                'barcode_id.require' => '非法请求',
            ]);
            $data = $this->request->only(['barcode_id', 'status'], 'get');
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
        }
        PlatformService::getInstance()->addBarcode($data)
            ? $this->success('操作成功')
            : $this->error('操作失败');
    }

    /**
     * 删除平台条码
     * @date 2021/01/16
     * @author longli
     */
    public function delete()
    {
        $brandId = $this->request->request("ids");
        if(empty($brandId)) $this->error('参数错误');
        ProductPlatformBarcode::destroy($brandId);
        $this->success('删除成功');
    }

    /**
     * 合并平台PDF条码
     * @date 2021/01/17
     * @author longli
     */
    public function merge()
    {
        $barId = $this->request->get("barcode_id");
        if(empty($barId)) $this->error("非法请求");
        $barCode = ProductPlatformBarcode::get($barId);
        if(empty($barCode) || empty($barCode->path_pdf)) $this->error("请先上传平台PDF文件");
        $rootPath = PlatformService::getRootPath($barCode->path_pdf);
        if(!is_file($rootPath)) $this->error("平台PDF文件不存在，请重新上传");
        if(($toPath = $this->mergeBarcode($rootPath, $barCode->merge_text)) === false)
            $this->error('合成失败请与技术人员联系');
        $barCode->merge_path_pdf = $toPath;
        $barCode->is_merge = ProductPlatformBarcode::IS_YES;
        $barCode->save();
        $this->success("生成完成");
    }

    /**
     * 合成条码
     * @param string $rootPath 平台 pdf 根路径
     * @param string $text 需要合成的文字
     * @return false|string 返回 false 合成失败，string 合成后的路径
     * @date 2021/04/23
     * @author longli
     */
    private function mergeBarcode($rootPath, $text = '')
    {
        if(!is_file($rootPath)) return false;
        $toPath = dirname($rootPath) . "/" . Tools::getRandStr(16) . ".pdf";
        if(!PlatformService::getInstance()->generatePlatformBarcode($rootPath, $toPath, $text)) return false;
        return PlatformService::hiddenRootPath($toPath);
    }
}